package fhp.hlhj.giantfold
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.view.Gravity
import android.widget.Toast
import com.gyf.barlibrary.ImmersionBar
import com.lzy.okgo.model.HttpParams
import fhp.hlhj.giantfold.customView.CustomPop
import fhp.hlhj.giantfold.customView.DownloadDialog
import fhp.hlhj.giantfold.event.RecreateEvent
import fhp.hlhj.giantfold.interfaces.IMain
import fhp.hlhj.giantfold.event.RefreshLoginEvent
import fhp.hlhj.giantfold.fragment.*
import fhp.hlhj.giantfold.interfaces.IPop
import fhp.hlhj.giantfold.interfaces.IVersion
import fhp.hlhj.giantfold.javaBean.ErroBean
import fhp.hlhj.giantfold.javaBean.GetKeyBean
import fhp.hlhj.giantfold.javaBean.VersionBean
import fhp.hlhj.giantfold.presenter.MainPresenter
import fhp.hlhj.giantfold.presenter.PopPresenter
import fhp.hlhj.giantfold.presenter.VersionPresenter
import fhp.hlhj.giantfold.servicess.NetWorkService
import fhp.hlhj.giantfold.utils.LogUtil
import fhp.hlhj.giantfold.utils.MyUtils
import fhp.hlhj.giantfold.utils.SPUtils
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : BaseActivity(), IMain, IPop, IVersion {
    private lateinit var mainPresenter:MainPresenter
    private lateinit var verSionPresenter:VersionPresenter
    private var spendFgm:SpendFgm?=null
    private var selfUnLoginFgm:SelfUnLoginFgm?=null
    private var selfLoginedFgm:SelfLoginedFgm?=null
    private var navFgm:NavFragment?=null
    private lateinit var popPresenter: PopPresenter
    private var type=2
    private lateinit var growMoneyFgm :GrowMoneyFgm
    override fun getContentId(): Int = R.layout.activity_main
    override fun initView() {
        startService(Intent(this,NetWorkService::class.java))
        setPer()
        initToken()
        spendFgm=SpendFgm()
        navFgm=NavFragment()
        growMoneyFgm=GrowMoneyFgm()
        selfLoginedFgm=SelfLoginedFgm()
        selfUnLoginFgm=SelfUnLoginFgm()

        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.rpLo,spendFgm)
        transaction.add(R.id.rpLo,navFgm)
        transaction.add(R.id.rpLo,growMoneyFgm)
        transaction.add(R.id.rpLo,selfLoginedFgm)
        transaction.add(R.id.rpLo,selfUnLoginFgm)
        transaction.commit()
//        版本
        verSionPresenter= VersionPresenter(this)
        verSionPresenter.getVersion()
        mainPresenter= MainPresenter(this)
        mainPresenter.getTaoKeToken()
        popPresenter= PopPresenter(this)

        val params = HttpParams()
        params.put("third_key","c087c1c6bac253c70a3c53f839794789")
        params.put("login_type",1)
        if (MyUtils.isNetworkAvailable(this)){
            mainPresenter.getKey(params)
        }else{
            MyUtils.toast("没有检查到网络连接，请确定你联网了")
        }
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .init()

    }
    private fun setPer() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                ||ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) run {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE,Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE), 0)
        }
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
//        popPresenter.judgePop()

    }
    override fun onResume() {
        super.onResume()
        LogUtil.log("onresume")
        if(Contents.userId.equals("0")) {
//            MyUtils.trans(supportFragmentManager,R.id.rpLo,selfUnLoginFgm)

        }else {
//            MyUtils.trans(supportFragmentManager,R.id.rpLo,selfLoginedFgm)
        }

    }
    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    /**
     * 获取淘客Token
     */
    override fun getToken(token: String) {
        LogUtil.log("获取到的Token="+token)
        Contents.taokeToken=token
    }

    override fun showLoaing() {
        LogUtil.log("开始获取Token")
    }
    override fun getKey(getKeyBean: GetKeyBean) {

    }
    override fun onError(erroBean: ErroBean) {


    }
    private fun initToken() {

    }

    @SuppressLint("ResourceType")
    override fun initData() {

    }
    @SuppressLint("ResourceType")
    override fun initListener() {
        bottomBar.setOnCheckedChangeListener { radioGroup, i ->
            LogUtil.log(radioGroup.checkedRadioButtonId.toString())
            when(i){
                R.id.rbMe->{
                    when(SPUtils.readLoginType(this)){
                        0,1,2->        {
                            val transaction = supportFragmentManager.beginTransaction()
                            transaction.show(selfLoginedFgm)
                            transaction.hide(selfUnLoginFgm)
                            transaction.hide(spendFgm)
                            transaction.hide(growMoneyFgm)
                            transaction.hide(navFgm)
                            transaction.commit()
                            Contents.enterType=1
                        }

                        -1->{
                            val transaction = supportFragmentManager.beginTransaction()
                            transaction.show(selfUnLoginFgm)
                            transaction.hide(selfLoginedFgm)
                            transaction.hide(spendFgm)
                            transaction.hide(growMoneyFgm)
                            transaction.hide(navFgm)
                            transaction.commit()
                            Contents.enterType=1
                        }
                    }

                }
                R.id.rbSpend->{
                    type=1
                    popPresenter.judgePop()
                    LogUtil.log(Contents.isLogin.toString())
                    popPresenter.judgePop()
                    val transaction = supportFragmentManager.beginTransaction()
                    transaction.show(spendFgm)
                    transaction.hide(growMoneyFgm)
                    transaction.hide(selfLoginedFgm)
                    transaction.hide(navFgm)
                    transaction.hide(selfUnLoginFgm)
                    transaction.commit()
                    Contents.enterType=3

                }
                R.id.rbGrow->{
                    type=3
                    popPresenter.judgePop()
                    val transaction = supportFragmentManager.beginTransaction()
                    transaction.show(growMoneyFgm)
                    transaction.hide(selfLoginedFgm)
                    transaction.hide(navFgm)
                    transaction.hide(spendFgm)
                    transaction.hide(selfUnLoginFgm)
                    transaction.commit()
                    Contents.enterType=3

                }
                else->{
                    type=2
                    popPresenter.judgePop()
                    val transaction = supportFragmentManager.beginTransaction()
                    transaction.show(navFgm)
                    transaction.hide(selfLoginedFgm)
                    transaction.hide(selfUnLoginFgm)
                    transaction.hide(spendFgm)
                    transaction.hide(growMoneyFgm)
                    transaction.commit()
                    Contents.enterType=2
                }
            }
        }
        bottomBar.check(R.id.rbSpend)
    }
    @SuppressLint("ResourceType")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun recreteAty(event:RecreateEvent){

    }
    public fun change(index:Int){
        /*selfLoginedFgm?.reSet()
        growMoneyFgm?.reSet()*/
        bottomBar.check(index)
    }
    override fun judgeTime() {
        val times = SPUtils.readTime(this, type)
        if (null==times){
//            第一次进入，存入时间戳信息
            SPUtils.saveTime(this,type,System.currentTimeMillis().toString())
        }else{
            var timeStamp:Long=times.toLong()
            if (times.length >= 11) {
                timeStamp = times.toLong() / 1000.toLong()
            }
            val t = System.currentTimeMillis() - timeStamp
            if (t<=60*60*3){
                return
            }else{
                SPUtils.saveTime(this,type,System.currentTimeMillis().toString())
            }

        }
    }

    override fun getVersion(versionBean: VersionBean) {
        if (versionBean.code==200){
            LogUtil.log("版本为"+MyUtils.getVersion(this).toString())
            if (versionBean.data.version.equals(MyUtils.getVersion(this))){

            }else{
                AlertDialog.Builder(this).setTitle("版本更新")
                        .setMessage(versionBean.data.description)
                        .setPositiveButton("更新"){
                            dialog, which ->
                            DownloadDialog(this,versionBean.data.savename,this).show()
                        }
                        .setNegativeButton("取消"){
                            dialog, which ->
                            dialog.dismiss()
                        }
                        .show()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!= Activity.RESULT_OK)return
        if (requestCode==2){
           /* selfLoginedFgm?.reSet()
            growMoneyFgm?.reSet()*/
            bottomBar.check(R.id.rbSpend)

            LogUtil.log("---------------成功回到MainAty")
        }
    }
}
